package ms.unicorn.diagram.edit.parts;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import ms.unicorn.Element;
import ms.unicorn.diagram.edit.policies.EntityItemSemanticEditPolicy;
import ms.unicorn.diagram.part.UnicornVisualIDRegistry;
import ms.unicorn.diagram.providers.UnicornElementTypes;
import ms.unicorn.modellanguage.LanguageElement;
import ms.unicorn.modellanguage.LanguageEntity;
import ms.unicorn.modellanguage.LanguageRegistry;
import ms.unicorn.ui.edit.parts.IEntityEditPart;
import ms.unicorn.ui.edit.parts.IGraphicalEditPartEx;
import ms.unicorn.util.FigureConstant;

import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.Graphics;
import org.eclipse.draw2d.GridData;
import org.eclipse.draw2d.GridLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.RectangleFigure;
import org.eclipse.draw2d.Shape;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.gef.ConnectionEditPart;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.Request;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.editpolicies.LayoutEditPolicy;
import org.eclipse.gef.editpolicies.NonResizableEditPolicy;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.ShapeNodeEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.draw2d.ui.figures.WrappingLabel;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.gef.ui.figures.DefaultSizeNodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.swt.graphics.Color;

/**
 * @generated NOT
 */
public class EntityEditPart extends ShapeNodeEditPart implements IEntityEditPart, IGraphicalEditPartEx {

	/**
	 * @generated
	 */
	public static final int VISUAL_ID = 2001;

	/**
	 * @generated
	 */
	protected IFigure contentPane;

	/**
	 * @generated
	 */
	protected IFigure primaryShape;

	protected WrappingLabel nameFigure, stereotypeFigure;

	protected Map<String, IFigure> figures;
	
	/**
	 * @generated
	 */
	public EntityEditPart(View view) {
		super(view);
	}

	/**
	 * @generated
	 */
	protected void createDefaultEditPolicies() {
		super.createDefaultEditPolicies();
		installEditPolicy(EditPolicyRoles.SEMANTIC_ROLE,
				new EntityItemSemanticEditPolicy());
		installEditPolicy(EditPolicy.LAYOUT_ROLE, createLayoutEditPolicy());
		// XXX need an SCR to runtime to have another abstract superclass that would let children add reasonable editpolicies
		// removeEditPolicy(org.eclipse.gmf.runtime.diagram.ui.editpolicies.EditPolicyRoles.CONNECTION_HANDLES_ROLE);
	}

	@Override
	public EditPolicy getPrimaryDragEditPolicy() {
		Element element = (Element) resolveSemanticElement();
		if (element != null) {
			LanguageElement lang = LanguageRegistry.INSTANCE.getLanguageElement(element);
			if (lang != null) {
				EditPolicy policy = lang.getEditHelperAdvice().createPrimaryDragEditPolicy(element, this);
				if (policy != null)
					return policy;
			}
		}
		return super.getPrimaryDragEditPolicy();
	}
	
	/**
	 * @generated
	 */
	protected LayoutEditPolicy createLayoutEditPolicy() {
		org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy lep = new org.eclipse.gmf.runtime.diagram.ui.editpolicies.LayoutEditPolicy() {

			protected EditPolicy createChildEditPolicy(EditPart child) {
				EditPolicy result = child
						.getEditPolicy(EditPolicy.PRIMARY_DRAG_ROLE);
				if (result == null) {
					result = new NonResizableEditPolicy();
				}
				return result;
			}

			protected Command getMoveChildrenCommand(Request request) {
				return null;
			}

			protected Command getCreateCommand(CreateRequest request) {
				return null;
			}
		};
		return lep;
	}

	/**
	 * @param figure 
	 * @generated NOT
	 */
	protected IFigure createNodeShape(NodeFigure figure) {
		primaryShape = new EntityFigure();
		nameFigure = ((EntityFigure) primaryShape).getFigureEntityNameFigure();
		stereotypeFigure = ((EntityFigure) primaryShape).getFigureStereotypeFigure();
		figure.add(primaryShape);
		
		return primaryShape;
	}

	/**
	 * @generated
	 */
	public IFigure getPrimaryShape() {
		return (IFigure) primaryShape;
	}

	/**
	 * @generated NOT
	 */
	protected boolean addFixedChild(EditPart childEditPart) {
		if (childEditPart instanceof EntityNameTextEditPart) {
			boolean vis = nameFigure.isVisible();
			((EntityNameTextEditPart) childEditPart)
					.setLabel(nameFigure);
			nameFigure.setVisible(vis);
			return true;
		}
		if (childEditPart instanceof EntityStereotypeTextEditPart) {
			boolean vis = stereotypeFigure.isVisible();
			((EntityStereotypeTextEditPart) childEditPart).setLabel(stereotypeFigure);
			stereotypeFigure.setVisible(vis);
			return true;
		}
		return false;
	}

	/**
	 * @generated
	 */
	protected boolean removeFixedChild(EditPart childEditPart) {
		if (childEditPart instanceof EntityNameTextEditPart) {
			return true;
		}
		if (childEditPart instanceof EntityStereotypeTextEditPart) {
			return true;
		}
		return false;
	}

	/**
	 * @generated
	 */
	protected void addChildVisual(EditPart childEditPart, int index) {
		if (addFixedChild(childEditPart)) {
			return;
		}
		super.addChildVisual(childEditPart, -1);
	}

	/**
	 * @generated
	 */
	protected void removeChildVisual(EditPart childEditPart) {
		if (removeFixedChild(childEditPart)) {
			return;
		}
		super.removeChildVisual(childEditPart);
	}

	/**
	 * @generated
	 */
	protected IFigure getContentPaneFor(IGraphicalEditPart editPart) {
		return getContentPane();
	}

	/**
	 * @generated
	 */
	protected NodeFigure createNodePlate() {
		DefaultSizeNodeFigure result = new DefaultSizeNodeFigure(40, 40) {
			@Override
			public void setBounds(Rectangle rect) {
				// TODO Auto-generated method stub
				super.setBounds(rect);
			}
		};
		return result;
	}

	/**
	 * Creates figure for this edit part.
	 * 
	 * Body of this method does not depend on settings in generation model
	 * so you may safely remove <i>generated</i> tag and modify it.
	 * 
	 * @generated NOT
	 */
	protected NodeFigure createNodeFigure() {
		Element element = (Element) resolveSemanticElement();
		LanguageElement lang = LanguageRegistry.INSTANCE.getLanguageElement(element);
		
		if (lang instanceof LanguageEntity) {
			figures = lang.getEditHelperAdvice().createFigures(null, element, this);
			if (figures != null) {
				primaryShape = figures.get(FIGURE_ELEMENT_PRIMARY_SHAPE);
				nameFigure = (WrappingLabel) figures.get(FIGURE_ELEMENT_NAME);
				stereotypeFigure = (WrappingLabel) figures.get(FIGURE_ELEMENT_STEREOTYPE);
				contentPane = figures.get(FIGURE_ELEMENT_CONTENT_PANE);
				NodeFigure figure = (NodeFigure) figures.get(FIGURE_ELEMENT_PLATE);
				return figure;
			}
				
		}
		return createNodeFigureGen(); 		
	}
	
	protected NodeFigure createNodeFigureGen() {
		NodeFigure figure = createNodePlate();
		figure.setLayoutManager(new StackLayout());
		// createNodeShape takes responsibility to add shape to the node plate.
		IFigure shape = createNodeShape(figure);
		// figure.add(shape);
		contentPane = setupContentPane(shape);
		return figure;
	}

	/**
	 * Default implementation treats passed figure as content pane.
	 * Respects layout one may have set for generated figure.
	 * @param nodeShape instance of generated figure class
	 * @generated
	 */
	protected IFigure setupContentPane(IFigure nodeShape) {
		if (nodeShape.getLayoutManager() == null) {
			ConstrainedToolbarLayout layout = new ConstrainedToolbarLayout();
			layout.setSpacing(5);
			nodeShape.setLayoutManager(layout);
		}
		return nodeShape; // use nodeShape itself as contentPane
	}

	/**
	 * @generated NOT
	 */
	public IFigure getContentPane() {
		if (contentPane != null) {
			return contentPane;
		}
		return super.getContentPane();
	}

	protected void setContenPane(IFigure contentPane) {
		this.contentPane = contentPane;
	}

	/**
	 * @generated
	 */
	protected void setForegroundColor(Color color) {
		if (primaryShape != null) {
			primaryShape.setForegroundColor(color);
		}
	}

	/**
	 * @generated
	 */
	protected void setBackgroundColor(Color color) {
		if (primaryShape != null) {
			primaryShape.setBackgroundColor(color);
		}
	}

	/**
	 * @generated
	 */
	protected void setLineWidth(int width) {
		if (primaryShape instanceof Shape) {
			((Shape) primaryShape).setLineWidth(width);
		}
	}

	/**
	 * @generated
	 */
	protected void setLineType(int style) {
		if (primaryShape instanceof Shape) {
			((Shape) primaryShape).setLineStyle(style);
		}
	}

	/**
	 * @generated
	 */
	public EditPart getPrimaryChildEditPart() {
		return getChildBySemanticHint(UnicornVisualIDRegistry
				.getType(EntityNameTextEditPart.VISUAL_ID));
	}
	
	@Override
	public ConnectionAnchor getSourceConnectionAnchor(Request request) {
		ConnectionAnchor anchor = super.getSourceConnectionAnchor(request);
		return anchor;
	}
	
	@Override
	public ConnectionAnchor getSourceConnectionAnchor(
			ConnectionEditPart connEditPart) {
		ConnectionAnchor anchor = super.getSourceConnectionAnchor(connEditPart);
		return anchor;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMARelTypesOnSource() {
		ArrayList<IElementType> types = new ArrayList<IElementType>(1);
		types.add(UnicornElementTypes.Relation_4001);
		return types;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMARelTypesOnSourceAndTarget(
			IGraphicalEditPart targetEditPart) {
		LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (targetEditPart instanceof ms.unicorn.diagram.edit.parts.EntityEditPart) {
			types.add(UnicornElementTypes.Relation_4001);
		}
		return types;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMATypesForTarget(IElementType relationshipType) {
		LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (relationshipType == UnicornElementTypes.Relation_4001) {
			types.add(UnicornElementTypes.Entity_2001);
		}
		return types;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMARelTypesOnTarget() {
		ArrayList<IElementType> types = new ArrayList<IElementType>(1);
		types.add(UnicornElementTypes.Relation_4001);
		return types;
	}

	/**
	 * @generated
	 */
	public List<IElementType> getMATypesForSource(IElementType relationshipType) {
		LinkedList<IElementType> types = new LinkedList<IElementType>();
		if (relationshipType == UnicornElementTypes.Relation_4001) {
			types.add(UnicornElementTypes.Entity_2001);
		}
		return types;
	}

	@Override
	protected void handleNotificationEvent(Notification notification) {
		// TODO Auto-generated method stub
		super.handleNotificationEvent(notification);
		
		Object feature = notification.getFeature();
		if (feature instanceof EAttribute) {
			EAttribute attr = (EAttribute) feature;
			if ("stereotype".equals(attr.getName())) {
				String value = notification.getNewStringValue();
				if (stereotypeFigure != null)
					stereotypeFigure.setVisible(value != null && value.length() > 0);
			}
		}
	}
	
	/**
	 * @generated
	 */
	public class EntityFigure extends RectangleFigure {

		/**
		 * @generated
		 */
		private WrappingLabel fFigureEntityNameFigure;

		/**
		 * @generated
		 */
		private WrappingLabel fFigureStereotypeFigure;

		/**
		 * @generated
		 */
		public EntityFigure() {

			GridLayout layoutThis = new GridLayout();
			layoutThis.numColumns = 1;
			layoutThis.makeColumnsEqualWidth = true;
			this.setLayoutManager(layoutThis);

			this.setLineStyle(Graphics.LINE_CUSTOM);
			createContents();
		}

		/**
		 * @generated
		 */
		private void createContents() {

			fFigureStereotypeFigure = new WrappingLabel();
			fFigureStereotypeFigure.setText("");

			GridData constraintFFigureStereotypeFigure = new GridData();
			constraintFFigureStereotypeFigure.verticalAlignment = GridData.CENTER;
			constraintFFigureStereotypeFigure.horizontalAlignment = GridData.CENTER;
			constraintFFigureStereotypeFigure.horizontalIndent = 0;
			constraintFFigureStereotypeFigure.horizontalSpan = 1;
			constraintFFigureStereotypeFigure.verticalSpan = 1;
			constraintFFigureStereotypeFigure.grabExcessHorizontalSpace = false;
			constraintFFigureStereotypeFigure.grabExcessVerticalSpace = false;
			this.add(fFigureStereotypeFigure, constraintFFigureStereotypeFigure);

			fFigureEntityNameFigure = new WrappingLabel();
			fFigureEntityNameFigure.setText("<...>");

			GridData constraintFFigureEntityNameFigure = new GridData();
			constraintFFigureEntityNameFigure.verticalAlignment = GridData.CENTER;
			constraintFFigureEntityNameFigure.horizontalAlignment = GridData.CENTER;
			constraintFFigureEntityNameFigure.horizontalIndent = 1;
			constraintFFigureEntityNameFigure.horizontalSpan = 1;
			constraintFFigureEntityNameFigure.verticalSpan = 1;
			constraintFFigureEntityNameFigure.grabExcessHorizontalSpace = false;
			constraintFFigureEntityNameFigure.grabExcessVerticalSpace = false;
			this.add(fFigureEntityNameFigure, constraintFFigureEntityNameFigure);

		}

		/**
		 * @generated
		 */
		public WrappingLabel getFigureEntityNameFigure() {
			return fFigureEntityNameFigure;
		}

		/**
		 * @generated
		 */
		public WrappingLabel getFigureStereotypeFigure() {
			return fFigureStereotypeFigure;
		}

	}

	@Override
	public IFigure getPrimaryFigure() {
		return primaryShape;
	}

	@Override
	public IFigure getFigure(String figID) {
		return figures.get(figID);
	}

	@Override
	public Collection<IFigure> getFigures() {
		return figures.values();
	}

}
